<template>
  <div v-if="isShow" relative>
    <navbar @click="handleClickNavbarItem" :scroll="scroll" />
    <div id="mark-goods">
      <goodsSwiper :res="goodsInfo" />
      <goodsPromotionPin v-if="goodsInfo" :res="goodsInfo" />
      <goodsBase @share="share" :res="goodsInfo" />
      <!-- 拼团用户列表 -->
      <div class="card" v-if="goodsPromotionType === 'pintuan'">
        <div class="goods-active" :style="gradient">拼购列表</div>
        <div mt-20rpx>
          <goodsGroupUserList @click="join" :res="goodsInfo" />
        </div>
      </div>
      <goodsCard @click="control" :sku="currentSku" :res="goodsInfo" />
    </div>
    <!-- 评价 -->
    <div class="card" id="mark-comment">
      <div :style="gradient">
        <div flex flex-a-c flex-j-sb>
          <div class="goods-active">
            评价
            <span font-400 text-24rpx>{{ commentInfo?.total || 0 }}+</span>
          </div>
          <div text-24rpx color-warmGray>
            好评率 {{ goodsInfo?.data?.grade || '100' }}%
          </div>
        </div>
      </div>

      <goodsComment :id="routerVal.goodsId" @result="(val) => { commentInfo = val }" />
    </div>
    <!-- 店铺 -->
    <div class="card">
      <goodsStore :id="goodsInfo?.data?.storeId" />
    </div>
    <!-- 商品介绍 -->
    <div class="card" id="mark-intro">
      <div class="goods-active" :style="gradient">商品介绍</div>
      <goodsIntro :res="goodsInfo?.data.mobileIntro" />
    </div>
    <!-- 商品参数 -->
    <div class="card">
      <div class="goods-active" :style="gradient">商品参数</div>
      <goodsParams :res="goodsInfo?.goodsParamsDTOList" />
    </div>
    <!-- 宝贝推荐 -->
    <div class="card" id="mark-recommend">
      <div class="goods-active" :style="gradient">宝贝推荐</div>
      <goodsRecommend :res="goodsInfo?.data" />
    </div>
    <div w-full position-fixed bottom-0>
      <goodsTabbar :info="goodsInfo" :storeId="goodsInfo?.data?.storeId" :carts="cartsCount" @click="buy" />
    </div>

    <shareModel ref="shareRef" />
    <nut-toast ref="toastRef" />
    <goodsSku :info="goodsInfo" @click="fetchSku" ref="skuRef" @bill="bill" :goods="sku.goods"
      :salesModel="sku.salesModel" />
  </div>
</template>

<script setup lang="ts">
import { getGoodsDistribution } from '@/api/goods';
import { billOrder, getCartCount } from '@/api/trade';
import { parseScene } from '@/api/common';
import Goods from '@/components/goods/template/functions';
import goodsBase from '@/components/goods/template/goods-base.vue';
import goodsCard from '@/components/goods/template/goods-card.vue';
import goodsComment from '@/components/goods/template/goods-comment.vue'; //商品评价
import goodsIntro from '@/components/goods/template/goods-intro.vue'; //商品介绍
import goodsParams from '@/components/goods/template/goods-params.vue'; //商品参数
import goodsRecommend from '@/components/goods/template/goods-recommend.vue'; //商品推荐
import goodsStore from '@/components/goods/template/goods-store.vue'; //当前商品店铺
import goodsSwiper from '@/components/goods/template/goods-swiper.vue'; //商品轮播
import goodsTabbar from '@/components/goods/template/goods-tabbar.vue'; //商品底部
import goodsGroupUserList from '@/components/goods/template/promotion/goods-group-list.vue';
import goodsPromotionPin from '@/components/goods/template/promotion/goods-promotion-pin.vue';
import shareModel from '@/components/share/index.vue';
import goodsSku from '@/components/sku/index.vue'; //商品底部
import { colors } from '@/constants/injection-key';
import navbar from '@/pages/goods/product/goods-navbar.vue';
import storage from '@/utils/storage';
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';
import { isLogin, forceLogin } from '@/utils/filters';
// import { fetchGoodsDetail } from '@/components/goods/template/functions'
const gradient = { '--gradient-left': colors.themeColor, '--gradient-right': colors.disabledLightColor }
const goodsInfo = ref<any>('') //商品详情
const routerVal = ref<any>('')
const currentSku = ref<any>('') //当前的sku信息
const isShow = ref<boolean>(false)
const commentInfo = ref<any>('') //评论详情

const cartsCount = ref(0)
const skuRef = ref<any>()
const shareRef = ref<any>(null)
const hasComputeCalc = ref<boolean>(false)
const sku = ref<any>({
  salesModel: "",
  goods: ""
})
const scrollArr = ref<Array<{ label: string, value: number }>>([])
const scroll = ref<number>(0)
const billData = ref<any>({})
const toastRef = ref<ToastInst>()
const goodsPromotionType = ref<'' | 'pintuan' | 'seckill'>('') //
async function init() {
  // 获取商品详情
  fetchGoodsDetail()


  if (isLogin("auth")) {
    fetchCartCount()
  }
}

async function control(type: any) {
  const data: any = {
    'addr': () => {
      billData.value.addr = type.addr;

    },
    'skuSelectorOpen': () => { skuRef.value.open() }
  }
  Object.keys(type).forEach((key) => {
    data[key as keyof typeof type]();
  });
}


const linkPath = () => {
  return "/pages/goods/product/detail?skuId=" +
    routerVal.value.skuId +
    "&goodsId=" +
    routerVal.value.goodsId
}

// 分享
function share() {
  shareRef.value.fill(
    {
      title: goodsInfo.value.data.goodsName,
      href: linkPath(),
      imageUrl: goodsInfo.value.data.goodsGalleryList[0],
      type: 'goods'
    }
  )
  shareRef.value.open()
}


// 结账 加入购物车/立即购买
async function bill(val: any) {
  forceLogin()
  if (!isLogin("auth")) {
    return
  }
  let data = {
    skuId: val.skuId,
    num: val.num,
    cartType: val.type // BUY_NOW VIRTUAL PINTUAN
  };

  // 如果不是拼团或者_self为空的时候清除拼团数据
  if (val.type !== 'PINTUAN' || !val._self) storage.setJoinUserData('')
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const res = await billOrder(data);

  if (res.data.success) {
    // 加入购物车
    if (!data.cartType) {
      fetchCartCount(true)
    }
    else {
      toastRef.value?.hideToast();
      uni.navigateTo({
        url: `/pages/mine/order/fillorder?way=${data.cartType}`
      });
    }
  }
  else {
    toastRef.value?.hideToast();
  }
}

// 获取购物车数量
async function fetchCartCount(toast?: boolean) {
  const res = await getCartCount()
  toastRef.value?.hideToast();
  if (res.data.success) {
    cartsCount.value = res.data.result
    if (toast) {
      uni.showToast({
        title: '加入购物车成功',
        icon: "none"
      })
    }

  }
}

function join(event: any) {
  storage.setJoinUserData(event)
  skuRef.value.whoami = event
  skuRef.value.open()
}

function buy() {
  skuRef.value.whoami = ''
  skuRef.value.open()
}

// 重构商品数据
function refactorGoods() {
  sku.value.goods = {
    thumbnail: goodsInfo.value.data.thumbnail,
    quantity: goodsInfo.value.data.quantity,
    price: goodsInfo.value.data.price,
    specs: goodsInfo.value.specs, //规格商品详情中 specs 字段全部传入
    skuId: goodsInfo.value.data.id,
    goodsId: goodsInfo.value.data.goodsId
  }
}

function handleClickNavbarItem(val: string) {
  const current = scrollArr.value.findIndex((item) => item.label === val)
  uni.pageScrollTo({
    scrollTop: scrollArr.value[current].value - 44,
    duration: 300
  });
}

function calcSize() {
  let h = 0;
  let arr = [
    "goods",
    "comment",
    "intro",
    "recommend",
  ];
  arr.forEach((item) => {
    let view = uni.createSelectorQuery().select("#mark-" + item);
    console.log(view)
    view.fields({ rect: true, size: true, scrollOffset: true }, (data: any) => {
      console.log(data, 'data')
      // if (data && data.top) {
      //   h += data.top;
      // }
      scrollArr.value.push({
        label: item,
        value: data.top
      });
    }).exec();
  });
  hasComputeCalc.value = true;
}

// 获取商品详情
async function fetchGoodsDetail(val?: { skuId: string, goodsId: string }) {
  const { skuId, goodsId } = val || routerVal.value
  const res = await new Goods(skuId, goodsId).fetch()
  isShow.value = true
  if (res.data.success) {
    goodsInfo.value = res.data.result
    // 整理商品数据
    refactorGoods()
  }
  // 这里是绑定分销员
  if (routerVal.value.distributionId) {
    console.log('分销id',routerVal.value.distributionId)
    await getGoodsDistribution(routerVal.value.distributionId);
  }

  // 判断当前商品商品类型
  if (res.data.result.promotionMap) {
    Object.keys(res.data.result.promotionMap).forEach((item) => {
      // 拼团商品
      if (item.indexOf("PINTUAN") === 0) {
        goodsPromotionType.value = 'pintuan'
      }

      // 秒杀
      if (item.indexOf("SECKILL") === 0) {
        goodsPromotionType.value = "seckill";
      }
    });
    goodsInfo.value.data.___promotion = goodsPromotionType.value
  }
}
// 根据skuId goodsId重新获取商品详情
function fetchSku(val: any) {
  const { skuId, goodsId } = val
  currentSku.value = val
  if (skuId) {
    fetchGoodsDetail({ skuId, goodsId })
  }
}



onLoad(async (options:any) => {
  if (options.scene) {
    // 获取真实scene参数
    const scene = await parseScene(decodeURIComponent(options.scene))
    console.log('真实参数',scene)
    const [skuId, goodsId, distributionId] = scene.split(',');
    routerVal.value = { skuId, goodsId, distributionId };
    init()
    return;
  }
  routerVal.value = options
  
})
onShow(() => {
  if (routerVal.value.skuId && routerVal.value.goodsId) {
    init()
  }
})


onPageScroll((e) => {
  if (!hasComputeCalc.value) {
    calcSize();
  }
  scroll.value = e.scrollTop
})

</script>

<style scoped lang="scss">
.card {
  margin: 20rpx 0;
  padding: 32rpx;
}

.goods-active {
  font-weight: 700;
  position: relative;
  display: inline;
  line-height: 1.75;

  &::before {
    position: absolute;
    left: 50%;
    bottom: -10rpx;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    content: "";
    display: block;
    width: 52rpx;
    height: 6rpx;
    background-image: linear-gradient(90deg, var(--gradient-left), var(--gradient-right))
  }
}
</style>
